from rest_framework.views import APIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from datetime import date, timedelta

from goods.models import GoodsVisitCount
from meiduo_admin.serialziers.serializers import UserGoodsCountSerializer
from users.models import User


class UserCountView(APIView):

    """
    用户总量统计

    """
    #权限指定
    permission_classes = [IsAdminUser]
    ##1.获取当前日期
    def get(self,request):
        now_date = date.today()
    #2.获取用户总量
        count = User.objects.all().count()
    #3.返回结果
        return  Response({
            'data':now_date,
            'cont':count
        })

class UserdaycountView(APIView):
    #权限限定
    permission_classes = [IsAdminUser]


    def get(self,request):
        #1.获取当天日期
        now_date = date.today()
        print(now_date)
        #2.获取当天注册的用户数量
        count = User.objects.filter(date_joined__gte=now_date).count()
        #3.返回结果
        return Response({
            'date':now_date,
            'count':count

        })

class UseractivateView(APIView):
    # 权限限定
    permission_classes = [IsAdminUser]

    def get(self,request):
        ##获取当前时间
        now_data = date.today()
        ##获取活跃用户，当天登录用户
        count = User.objects.filter(last_login__gte=now_data).count()
        #返回数据
        return Response({
            'data':now_data,
            'count':count
        })


class UseRorderView(APIView):
    # 权限限定
    permission_classes = [IsAdminUser]

    def get(self,request):
        #获取当前时间
        now_date = date.today()
        #获取下单用户数量
        count = len(set(User.objects.filter(orders__create_time__gte=now_date)))

        #返回数据
        return Response({
            'date':now_date,
            'count':count
        })



class UseMonthcountView(APIView):
    # 权限限定
    permission_classes = [IsAdminUser]
    def get(self,request):
        #获取当前日期
        now_date = date.today()
        #获取当前一个月之前的日期
        begin_date = now_date - timedelta(days=29)
        date_list=[]
        for day in range(30):
            #获取起始日期
            index_date = begin_date + timedelta(days=day)
            #获取第二天的日期(起始日期的下一天日期)
            next_date = begin_date + timedelta(days=day+1)
            #查询当前一天的注册用户数量
            count = User.objects.filter(date_joined__gte=index_date,
                                        date_joined__lt=next_date).count()
            date_list.append({
                'count':count,
                 'date':index_date
                 })
        return Response(date_list)

class UserGoodsView(APIView):
    # 权限限定
    permission_classes = [IsAdminUser]

    def get(self,request):
        ##获取当前时间
        now_data = date.today()
        ##根据当天日期 获取分类访问量

        goods = GoodsVisitCount.objects.filter(date__gte=now_data)

        ser = UserGoodsCountSerializer(goods,many=True)
        #返回数据
        return Response(ser.data)

